package com.maoxs.dao.impl;

import com.maoxs.dao.UserDao;
import com.maoxs.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDaoImpl implements UserDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加
     * @param user
     * @throws Exception
     */
    @Override
    public void add(User user) throws Exception {
        mongoTemplate.save(user);
    }

    /**
     * 根据id更新
     * @param user
     * @throws Exception
     */
    @Override
    public void update(User user) throws Exception {
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update = new Update().set("name", user.getName()).set("password", user.getPassword());
        mongoTemplate.updateFirst(query, update, User.class);
    }

    /**
     * 删除
     * @param id
     * @throws Exception
     */
    @Override
    public void delete(Long id) throws Exception {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query,User.class);
    }

    /**
     * 分页
     * @param page
     * @param size
     * @return
     * @throws Exception
     */
    @Override
    public  List<User>  select(int page,int size) throws Exception {
        //Query 用于复杂的mongodb查询
        Query query = new Query();
        query.skip(page*size).limit(size);
        List<User> users = mongoTemplate.find(query, User.class);
        return users;
    }
}
